//
//  MBLoginController.m
//  LiveBroadcast
//
//  Created by 肖剑 on 2019/2/15.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBLoginController.h"
#import "MITimerButton.h"
#import "MBSelectFishController.h"
#import "MBBindingPhoneController.h"
@interface MBLoginController ()
{
    NSMutableDictionary *_loginDict;
    UITextField *phoneTf;
}
@end

@implementation MBLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.    
    self.navigationController.navigationBar.hidden = YES;
    // 初始化属性
    _loginDict = [NSMutableDictionary dictionary];
    
    self.view.backgroundColor = [UIColor whiteColor];
    // 加载控件
    [self initView];
}

// 控件
- (void)initView
{
    // 头部
    UIImageView *logoImg = [[UIImageView alloc] init];
    logoImg.frame = CGRectMake((IPHONE_SCREEN_WIDTH - 90)/2,40,90,90);
    logoImg.image = [UIImage imageNamed:@"logo.png"];
    logoImg.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
    [self.view addSubview:logoImg];
    
    // 关闭按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(20, 20, 20, 40);
    [closeBtn setImage:[UIImage imageNamed:@"closex.png"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(closeLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:closeBtn];
    
    // 选中登录注册
    // 登录
    MBButton *selectLoginBtn = [MBButton buttonWithType:UIButtonTypeCustom];
    selectLoginBtn.frame = CGRectMake(logoImg.left - 20, logoImg.bottom + 40, 60, 44);
    [selectLoginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [selectLoginBtn.titleLabel setFont:[UIFont systemFontOfSize:20.0f]];
    selectLoginBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [selectLoginBtn setTitleColor:kColorRGBA(255, 128, 0, 1) forState:UIControlStateSelected];
    selectLoginBtn.selected = YES;
    [selectLoginBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:selectLoginBtn];
    
    UIView *lineView = [[UIView alloc]init];
    lineView.frame = CGRectMake(selectLoginBtn.left + (selectLoginBtn.width)/4, selectLoginBtn.bottom, selectLoginBtn.width / 2, 2);
    lineView.backgroundColor = selectLoginBtn.titleLabel.textColor;
    lineView.backgroundColor = selectLoginBtn.currentTitleColor;
    [self.view addSubview:lineView];
    // 注册
    MBButton *selectRegisterBtn = [MBButton buttonWithType:UIButtonTypeCustom];
    selectRegisterBtn.frame = CGRectMake(selectLoginBtn.right + 20, selectLoginBtn.top, selectLoginBtn.width, 44);
    [selectRegisterBtn setTitle:@"注册" forState:UIControlStateNormal];
    [selectRegisterBtn.titleLabel setFont:[UIFont systemFontOfSize:20.0f]];
    selectRegisterBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [selectRegisterBtn setTitleColor:kColorRGBA(255, 128, 0, 1) forState:UIControlStateSelected];
    [selectRegisterBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:selectRegisterBtn];
    
    UIView *rLineView = [[UIView alloc]init];
    rLineView.frame = CGRectMake(selectRegisterBtn.left + (selectRegisterBtn.width)/4, selectRegisterBtn.bottom, selectRegisterBtn.width / 2, 2);
    rLineView.backgroundColor = selectRegisterBtn.titleLabel.textColor;
    rLineView.hidden = YES;
    [self.view addSubview:rLineView];

    // 手机号码
    UILabel *phoneLbl = [[UILabel alloc]initWithFrame:CGRectMake(20, lineView.bottom + 40, 60, 60)];
    phoneLbl.text = @"+86";
    phoneLbl.textColor = kColorRGBA(51, 51, 51, 1);
    [self.view addSubview:phoneLbl];
    
    UIView *phoneLine = [[UIView alloc]initWithFrame:CGRectMake(phoneLbl.right + 10, phoneLbl.top, 0.5, phoneLbl.height)];
    phoneLine.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1.0];
    [self.view addSubview:phoneLine];
    
    phoneTf = [[UITextField alloc]initWithFrame:CGRectMake(phoneLine.right + 20, phoneLine.top, IPHONE_SCREEN_WIDTH - phoneLine.left -20, phoneLine.height)];
    phoneTf.placeholder = @"请输入手机号码";
    [self.view addSubview:phoneTf];
    
    UIView *phoneLine1 = [[UIView alloc] init];
    phoneLine1.frame = CGRectMake(phoneLbl.left,phoneLbl.bottom + 10,IPHONE_SCREEN_WIDTH - 40,0.5);
    phoneLine1.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1.0];
    [self.view addSubview:phoneLine1];
    
    // 验证码
    UILabel *codeLbl = [[UILabel alloc]initWithFrame:CGRectMake(20, phoneLine1.bottom + 10, 60, 60)];
    codeLbl.text = @"验证码";
    codeLbl.textColor = kColorRGBA(51, 51, 51, 1);
    [self.view addSubview:codeLbl];
    
    UITextField *codeTf = [[UITextField alloc]initWithFrame:CGRectMake(phoneTf.left, codeLbl.top, IPHONE_SCREEN_WIDTH - phoneTf.left - 100, codeLbl.height)];
    codeTf.placeholder = @"请输入验证码";
    [self.view addSubview:codeTf];
    
    //获取验证码
    MITimerButton *codeBtn= [MITimerButton buttonWithType:UIButtonTypeCustom];
    codeBtn.frame = CGRectMake(codeTf.right, codeTf.top + 10, 100, 40);
    [codeBtn setBackgroundColor:[UIColor whiteColor]];
    codeBtn.tag = 101;
    [codeBtn setTitleColor:kColorRGBA(255, 128, 0, 1) forState:UIControlStateNormal];
    [codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    codeBtn.isCountiue = NO;
    [codeBtn addTarget:self action:@selector(addCodeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:codeBtn];
    
    UIView *codeLine = [[UIView alloc] init];
    codeLine.frame = CGRectMake(phoneLbl.left,codeLbl.bottom + 10,IPHONE_SCREEN_WIDTH - 40,0.5);
    codeLine.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1.0];
    [self.view addSubview:codeLine];
    // 用户协议
    
    // 登录注册按钮
    MBButton *loginBtn = [MBButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake(40, codeLine.bottom + 60, IPHONE_SCREEN_WIDTH - 80, 44);
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setBackgroundColor:kColorRGBA(255, 128, 0, 1)];
    [loginBtn addTarget:self action:@selector(closeLogin) forControlEvents:UIControlEventTouchUpInside];
    loginBtn.layer.cornerRadius = 22;
    [self.view addSubview:loginBtn];
    // 微信登录
    MBButton *wxBtn = [MBButton buttonWithType:UIButtonTypeCustom];
    wxBtn.frame = CGRectMake(40, loginBtn.bottom + 20, IPHONE_SCREEN_WIDTH - 80, 44);
    [wxBtn.titleLabel setFont:[UIFont systemFontOfSize:15.0f]];
    [wxBtn setTitleColor:kColorRGBA(51, 51, 51, 1) forState:UIControlStateNormal];
    [wxBtn setTitle:@"微信登录" forState:UIControlStateNormal];
    [wxBtn setImage:[UIImage imageNamed:@"wechat.png"] forState:UIControlStateNormal];
    [wxBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 15, 0, 0)];
    [wxBtn addTarget:self action:@selector(closeLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:wxBtn];

    
    //---------------------------------------------事件处理-------------------------------------------------------
    __block MBButton *rSelectLoginBtn = selectLoginBtn;
    __block MBButton *rSelectRegisterBtn = selectRegisterBtn;
    // 登录选项
    selectLoginBtn.miBtnBlock = ^(){
        rSelectLoginBtn.selected = YES;
        lineView.backgroundColor = rSelectLoginBtn.currentTitleColor;
        lineView.hidden = NO;
        rSelectRegisterBtn.selected = NO;
        rLineView.backgroundColor = rSelectRegisterBtn.currentTitleColor;
        rLineView.hidden = YES;
        
        [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    };
    // 注册选项
    selectRegisterBtn.miBtnBlock = ^(){
        rSelectRegisterBtn.selected = YES;
        rLineView.backgroundColor = rSelectRegisterBtn.currentTitleColor;
        rLineView.hidden = NO;
        rSelectLoginBtn.selected = NO;
        lineView.backgroundColor = rSelectLoginBtn.currentTitleColor;
        lineView.hidden = YES;
        
        [loginBtn setTitle:@"注册" forState:UIControlStateNormal];

    };
    
    __block MBButton *rLoginBtn = loginBtn;
    MBSelectFishController *fishCtr = [[MBSelectFishController alloc]init];
    MBBindingPhoneController *bindingCtr = [[MBBindingPhoneController alloc]init];
    loginBtn.miBtnBlock = ^(){
        // 校验验证码
        if (codeTf.text.length != 0 || [codeTf.text isEqualToString:self->_loginDict[@"code"]]) {
            
            if (self->phoneTf.text.length != 0) {
                if ([rLoginBtn.currentTitle isEqualToString:@"登录"]) {
                    [MBHttpRequset requestWithUrl:kTradeid_login_login setParams:@{@"phone":self->phoneTf.text} isShowProgressView:YES success:^(id  _Nonnull AJson) {
                        [[RCIM sharedRCIM] connectWithToken:AJson[@"token"]  success:^(NSString *userId) {
                            NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
                            MBUserModel *userModel = [MBUserModel shareInstanceWithDict:AJson];
                            [MBUserModel sharedMBUserModel].isLoginFlag = YES;
                            [self archiveDatas:userModel];
                            NSLog(@"==========================userInfo  %@",userModel.userInfo.headUrl);
                            [[NSNotificationCenter defaultCenter] postNotificationName:MBIsLoginNotification object:nil userInfo:@{@"isFlag":MBLoginFLag}];
                            NSLog(@"登录成功====================userInfo  %@",userModel.userInfo.headUrl);
                        } error:^(RCConnectErrorCode status) {
                            [MBProgressHUD showError:[NSString stringWithFormat:@"登陆的错误码为:%ld", (long)status]];
                        } tokenIncorrect:^{
                            //token过期或者不正确。
                            //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
                            //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
                            [MBProgressHUD showError:@"token错误"];
                        }];

                        
                        MBUserModel *userModel = [MBUserModel shareInstanceWithDict:AJson];
                        [MBUserModel sharedMBUserModel].isLoginFlag = YES;
                        
                        [self archiveDatas:userModel];
                        
                        
                        NSLog(@"==========================userInfo  %@",userModel.userInfo.headUrl);
                        [[NSNotificationCenter defaultCenter] postNotificationName:MBIsLoginNotification object:nil userInfo:@{@"isFlag":MBLoginFLag}];
                        [self tencentChatLoginWith:userModel];
                    } failure:^(id  _Nonnull AJson) {
                        
                    }];
                }else{
                    [MBHttpRequset requestWithUrl:kTradeid_login_regist setParams:@{@"phone":self->phoneTf.text} isShowProgressView:YES success:^(id  _Nonnull AJson) {
                        // 注册成功自动登录
                        [MBHttpRequset requestWithUrl:kTradeid_login_login setParams:@{@"phone":self->phoneTf.text} isShowProgressView:YES success:^(id  _Nonnull AJson) {
                            
                            [[RCIM sharedRCIM] connectWithToken:AJson[@"token"]  success:^(NSString *userId) {
                                NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
                                MBUserModel *userModel = [MBUserModel shareInstanceWithDict:AJson];
                                [MBUserModel sharedMBUserModel].isLoginFlag = YES;
                                [self archiveDatas:userModel];
                                NSLog(@"注册自动登录====================userInfo  %@",userModel.userInfo.headUrl);
                                [[NSNotificationCenter defaultCenter] postNotificationName:MBIsLoginNotification object:nil userInfo:@{@"isFlag":MBLoginFLag}];
                                [self.navigationController pushViewController:fishCtr animated:YES];
                                NSLog(@"登录成功====================userInfo  %@",userModel.userInfo.headUrl);
                            } error:^(RCConnectErrorCode status) {
                                [MBProgressHUD showError:[NSString stringWithFormat:@"登陆的错误码为:%ld", (long)status]];
                            } tokenIncorrect:^{
                                //token过期或者不正确。
                                //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
                                //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
                                [MBProgressHUD showError:@"token错误"];
                            }];
                            MBUserModel *userModel = [MBUserModel shareInstanceWithDict:AJson];
                            [MBUserModel sharedMBUserModel].isLoginFlag = YES;
                            [self archiveDatas:userModel];
                            NSLog(@"自动登录====================userInfo  %@",userModel.userInfo.headUrl);
                             [[NSNotificationCenter defaultCenter] postNotificationName:MBIsLoginNotification object:nil userInfo:@{@"isFlag":MBLoginFLag}];
                            [self.navigationController pushViewController:fishCtr animated:YES];
                            [self tencentChatLoginWith:userModel];
                        } failure:^(id  _Nonnull AJson) {
                            
                        }];
                    } failure:^(id  _Nonnull AJson) {
                        
                    }];
                    
                }
            }else{
                //            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                return ;
            }
            
        }else{
            //            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        }
        
        
        
    };
    
    
    wxBtn.miBtnBlock = ^(){
        [self.navigationController pushViewController:bindingCtr animated:YES];
        
    };
    
    
    
    
}

// 退出登录页
- (void)closeLogin
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:CancelLoginNotificationKey object:nil];
}

// 获取验证码
- (void)addCodeBtnClick:(MITimerButton *)btn
{
    NSString *phone = phoneTf.text;
    if (phone.length != 0) {
        btn.isCountiue = YES;
        NSDictionary *dict =@{@"tel":phone,@"type":@"1"};
        [MBHttpRequset requestWithUrl:kTradeid_login_sendSms setParams:dict isShowProgressView:NO success:^(id  _Nonnull AJson) {
            NSLog(@"kTradeid_login_sendSms == %@",AJson);
            [self->_loginDict setObject:AJson forKey:@"code"];
        } failure:^(id  _Nonnull AJson) {
            
        }];
    }else{
        [MBProgressHUD showError:@"请输入正确的手机号码"];
        return;
    }
    
   
}


- (BOOL) validateMobile:(NSString* )mobile {
    //手机号以13， 15，18，17，19开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[0-9])|(18[0,0-9])|(17[0,0-9])|(19[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:mobile];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
/*登陆腾讯IM*/
-(void)tencentChatLoginWith:(MBUserModel *)model{
    TIMLoginParam * login_param = [[TIMLoginParam alloc ]init];
    // identifier 为用户名，userSig 为用户登录凭证
    // appidAt3rd 在私有帐号情况下，填写与 sdkAppId 一样
    login_param.identifier = [NSString stringWithFormat:@"%@",model.userInfo.userId];
    login_param.userSig = model.userSig;
    login_param.appidAt3rd = [NSString stringWithFormat:@"%i",TencentChatAppid];
    [[TIMManager sharedInstance] login: login_param succ:^(){
        NSLog(@"Login Succ");
    } fail:^(int code, NSString * err) {
        NSLog(@"Login Failed: %d->%@", code, err);
    }];
}
@end
